package com.dropTables.TakingNote;

import java.util.ArrayList;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.SystemClock;

public class SecificLocService extends IntentService 
{
	private static long WAIT_TIME = 5;
	private static float reminder_dist = 1000;
	private static ArrayList<Long> ids;
	private static ArrayList<Location> desireds;
	public SecificLocService()
	{
        super("SecificLocService");
    }
    @Override
      protected void onHandleIntent(Intent intent) {
    	
    	Bundle extras = intent.getExtras();
    	if(ids == null)
    		ids = new ArrayList<Long>();
    	if(desireds == null)
    		desireds = new ArrayList<Location>();
    	
    	//Initialize strings
    	String full = "pizza", name = "Origin", title = "Reminder";
    	double lat = 0, lng = 0, distance;
    	long id = 1;
    	if(extras!=null)		//Get data passed to intent
    	{
    		full = extras.getString("location");
    		id = extras.getLong("reminder-id");
    		ids.add(id);
    		String lst[] = full.split(":");			//Split location into title and gps
    		if (lst.length > 1)						//Split gps into latitude and longitude and convert to doubles
    		{
	    		String lst2[] = lst[1].split(",");
	    		lat = Double.valueOf(lst2[0]);
	    		lng = Double.valueOf(lst2[1]);
	    		name = lst[0];
    		}
    	}
    	
    	// Acquire a reference to the system Location Manager
    	LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    	// Define a listener that responds to location updates
    	LocationListener locationListener = new LocationListener() {
    	    public void onLocationChanged(Location location) {
    	      // Called when a new location is found by the network location provider.
    	      //makeUseOfNewLocation(location);
    	    }

    	    public void onStatusChanged(String provider, int status, Bundle extras) {}

    	    public void onProviderEnabled(String provider) {}

    	    public void onProviderDisabled(String provider) {}
    	  };

    	// Register the listener with the Location Manager to receive location updates
    	String locationProvider = LocationManager.GPS_PROVIDER;
    	
    	
    	
    	//Set the desired location to right latitude and longitude
        Location desiredLocation = new Location(locationProvider);
    	desiredLocation.setLatitude(lat);
    	desiredLocation.setLongitude(lng);
    	
    	desireds.add(desiredLocation);
    	
    	while(ids.indexOf(id) >= 0)
    	{
    		locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);			//Ask for gps updates
        	
        	SystemClock.sleep(1000*60);
        	
        
        	
        	Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
        	while(lastKnownLocation == null)															//Wait for location
        	{
        		lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
        	}
        	while(lastKnownLocation.getAccuracy() < 50)
        		lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);				//Wait for accuracy
        	
        	System.out.println(lastKnownLocation);
        	locationManager.removeUpdates(locationListener);											//Stop gps because it drains battery
        	
        	
        	distance = lastKnownLocation.distanceTo(desiredLocation);
        	if( distance <= reminder_dist)																//If you're close enough to remind
        	{
        		Intent nearByInt = new Intent(this, NearbySpecActivity.class);							//Create a
        		nearByInt.putExtra(NearbySpecActivity.KEY_SPEC_NAME, name);
        		nearByInt.putExtra(NearbySpecActivity.KEY_SPEC_DIST, distance);
        		nearByInt.putExtra(NearbySpecActivity.KEY_SPEC_ID, id);
        		
        		NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                long when = System.currentTimeMillis();         // notification time
                Notification notification = new Notification(R.drawable.tn_icon, title, when);
                notification.defaults |= Notification.DEFAULT_SOUND;
                notification.flags |= Notification.FLAG_AUTO_CANCEL;
                PendingIntent contentIntent = PendingIntent.getActivity(this, 0, nearByInt , 0);
                notification.setLatestEventInfo(getApplicationContext(), "You're close", "You're next to "+name, contentIntent);
                nm.notify((int)id, notification);
        	}

        	
			SystemClock.sleep(1000*60*WAIT_TIME);
    	}
    	

    }
    
    /*
     * @param id the id of the reminder to be removed
     * 
     * A function to remove a reminder from the list of active reminders
     */
    public static void removeReminder(Long id)
    {
    	if(ids!=null && ids.size()>0)		//If there are reminders in the list
    	{
    		int index = ids.indexOf(id);
	    	if(index >= 0)					//If the reminder is in th elist
	    	{
	    		ids.remove(index);
	    		desireds.remove(index);
	    	}
    	}
    }
}
